<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="increment">+</button>
    <span id="box">0</span>
    <button id="decrement">-</button>
    <script src="./myRedux.js"></script>
    <script src="./middlewares/logger.js"></script>
    <script src="./middlewares/thunk.js"></script>
    <script>
        
        function enhancer (createStore) {
            return function (reducer, preloadedState) {
                // 获取原生的 store 对象
                var store = createStore(reducer, preloadedState)
                var dispatch = store.dispatch
                function _dispatch (action) {
                    if (typeof action === 'function') {
                        return action(dispatch)
                    }
                    dispatch(action)
                }
                // 在 store 对象的基础上进行修改
                return {
                    ...store,
                    dispatch: _dispatch
                }
            }
        }
        
        function reducer (state, action) {
            switch (action.type) {
                case 'increment':
                    return state + 1
                    break;
                case 'decrement':
                    return state - 1
                    break;
                default:
                    return state
            }
        }
        
        var rootReducer = combineReducers({counter: reducer})
        
        // 创建 store 
        var store = createStore(rootReducer, {counter: 100}, applyMiddleware(logger, thunk))
        
        store.subscribe(function () {
            // 获取最新的状态
            document.getElementById('box').innerHTML = store.getState().counter
        })
        
        var actions = bindActionCreators({increment, decrement}, store.dispatch)
        
        function increment () {
            return { type: 'increment' }
        }

        function decrement () {
            return { type: 'decrement' }
        }
        
        document.getElementById('increment').onclick = function () {
            // store.dispatch(function (dispatch) {
            //     setTimeout(() => {
            //         dispatch({type: 'increment'})
            //     }, 1000);
            // })
            actions.increment()
        }
        
        document.getElementById('decrement').onclick = function () {
            // store.dispatch({type: 'decrement'})
            actions.decrement()
        }
    </script>
</body>
</html>